import requestConfig from '@/config/requestConfig'
import { randomString } from '@/utils'

const { request } = requestConfig
export const useUpload = () => {
  const uploadOss = (t) => {
    return new Promise(function (r, n) {
      request({
        url: '/api/common/oss_sign',
        method: 'get',
      }).then(function (n: any) {
        if (1e4 !== n.code)
          return uni.showModal({
            title: '提示',
            content: '服务器授权失败',
            showCancel: !1,
          })
        var o = n.data,
          i = n.data.dir + randomString(16)
        t.indexOf('mp4') >= 0 ? (i += '.mp4') : (i += '.jpg')
        var a = {
          key: i,
          policy: o.policy,
          OSSAccessKeyId: o.accessid,
          success_action_status: '200',
          signature: o.signature,
        }
        uni.uploadFile({
          url: o.host,
          filePath: t,
          name: 'file',
          formData: a,
          success: function (e) {
            r((o.fileUrl || o.host) + '/' + i)
          },
          complete: function (t) {
            t.errMsg.indexOf('uploadFile:fail') >= 0 &&
              uni.showModal({
                title: '提示',
                content: '上传失败！',
                showCancel: !1,
              })
          },
        })
      })
    })
  }
  return {
    uploadOss,
  }
}
